package org.changs.control.ui.msg;

import org.changs.aplug.base.BasePresenter;
import org.changs.control.push.PushMsg;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import javax.inject.Inject;

import aplug.AppManager;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/9/14.
 */

public class MsgPresenter extends BasePresenter<MsgContract.V> implements MsgContract.P {
    private final AppManager appManager;

    @Inject
    public MsgPresenter(AppManager appManager) {
        this.appManager = appManager;
    }

    @Override
    public void attachView(MsgContract.V v) {
        super.attachView(v);
        EventBus.getDefault().register(this);
        getMsgList();
    }

    @Override
    public void detachView() {
        super.detachView();
        EventBus.getDefault().unregister(this);
    }



    /**
     * 获取消息列表
     */
    public void getMsgList() {
        getCompositeDisposable().add(appManager.getPushMsgHelper().loadAll()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(pushMsgs -> getMvpView().showMsgList(pushMsgs)));
    }

    /**
     * 删除消息提示
     *
     * @param pushMsg
     */
    public void delete(PushMsg pushMsg) {
        getCompositeDisposable().add(appManager.getPushMsgHelper().delete(pushMsg)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        getMvpView().showMessage("删除成功");
                        getMsgList();
                    } else {
                        getMvpView().showMessage("删除失败");
                    }
                }));
    }

    @Override
    public void clickClear() {
        getCompositeDisposable().add(appManager.getPushMsgHelper().clear()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        getMvpView().showMessage("清空成功");
                        getMsgList();
                    } else {
                        getMvpView().showMessage("清空失败");
                    }
                }));
    }


    @Subscribe
    public void onEvent(PushMsg pushMsg) {
        getMsgList();
    }

}
